<template>
  <div class="singer" ref="singer">
    <list-view @select="selectSinger" :data="singers" ref="list"></list-view>
    <router-view></router-view>
  </div>
</template>

<script type="text/ecmascript-6">
import ListView from "base/listview/listview";
import { mapMutations } from 'vuex'
import { playlistMixin } from 'common/js/mixin'
import Singer from "common/js/singer";

import {getAllSinger} from "api";

export default {
  mixins: [playlistMixin],
  data() {
    return {
      singers: []
    };
  },
  created() {
    this._getSingerList();
  },
  methods: {
    handlePlaylist(playlist) {
      const bottom = playlist.length > 0 ? '60px' : ''
      this.$refs.singer.style.bottom = bottom
      this.$refs.list.refresh()
    },
    selectSinger(singer) {  //子组件listView将item（即singers[]中对象的item）传过来
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer)  //通过mutations修改state的singer取值为item
    },
    _getSingerList() {
      getAllSinger().then(res => {
        if (res) {
          this.singers = this._normalizeSinger(res);
          //console.log(this.singers)
          //console.log(res)
        }
      });
    },
    _normalizeSinger(list) {
      let map = {
        hot: {
          title: '',
          items: []
        }
      };
      list.forEach((item, index) => {
        const key = item.firstLetter;
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          };
        }
        map[key].items.push(
          new Singer({
            id: item.id,
            name: item.name,
            avatar: `http://127.0.0.1:8888${item.pic}`
          })
      );
      });
      //为了得到有序列表 需要处理map
      let ret = [];
      for (let key in map) {
        let val = map[key];
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val);
        }
      }
      ret.sort((a, b) => {
        //排序
        return a.title.charCodeAt(0) - b.title.charCodeAt(0);
      });
      return ret;
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  components: {
    ListView
  }
};
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
.singer {
  position: fixed;
  top: 88px;
  bottom: 0;
  width: 100%;
}
</style>
